<template>
  <div class="avatar-container">
    <!-- 未登录显示登录按钮 -->
    <el-button v-if="!currentUser" type="primary" @click="handleLogin">
      登录
    </el-button>
    
    <!-- 已登录显示头像和下拉菜单 -->
    <el-dropdown v-else trigger="click">
      <el-avatar
        :size="40"
        :src="userAvatar"
        @error="handleAvatarError"
      >
        {{ userInitials }}
      </el-avatar>
      
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item disabled>个人信息</el-dropdown-item>
          <el-dropdown-item disabled>设置</el-dropdown-item>
          <el-dropdown-item divided @click="handleLogout">
            退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/userStore'
import router from '@/router'

// 模拟登录状态
const isLoggedIn = ref(false)
const userAvatar = ref('')
const userName = ref('')
const userStroe = useUserStore()
const currentUser = userStroe.user
// 获取用户名首字母作为头像备选显示
const userInitials = computed(() => {
  return currentUser.account[0]
})

// 头像加载失败处理
const handleAvatarError = () => {
  userAvatar.value = ''
}

// 登录处理
const handleLogin = () => {
  // 这里添加登录逻辑
  isLoggedIn.value = true
  userName.value = currentUser.account // 设置实际用户名
}

// 登出处理
const handleLogout = () => {
  isLoggedIn.value = false
  userAvatar.value = ''
  userName.value = ''
  userStroe.logout(currentUser)
  router.push('/login')
}
</script>

<style scoped>
.avatar-container {
  display: inline-flex;
  align-items: center;
}

.el-avatar {
  cursor: pointer;
  background-color: #409EFF;
  color: #fff;
}

.el-dropdown {
  display: flex;
  align-items: center;
}
</style>
